<template>
	<view class="container">
		<!-- 第一部分：搜索框、搜索按钮、加号生成按钮 -->
		<view class="section section1">
			<view class="search-box">
				<input v-model="searchQuery" placeholder="请输入关键词" class="search-input"/>
				<button class="search-btn" @click="search">搜索</button>
				<button class="generate-btn" @click="goToRecommendPage">生成</button>
			</view>
		</view>

		<!-- 第二部分：关键词组合 -->
		<view class="section section2">
			<scroll-view direction="vertical" class="keyword-list">
				<view class="keyword-row">
					<view
						v-for="(keyword, index) in filteredKeywords"
						:key="index"
						:class="['keyword-item', selectedKeywords.includes(keyword) ? 'selected' : '']"
						@click="toggleKeywordSelection(keyword)"
					>
						{{ keyword }}
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 第三部分：天气显示 -->
		<view class="section section3">
		  <!-- 上部分：勾选框和提示文本 -->
		  <view class="section3-top">
		    <checkbox-group class="checkbox-container" @change="checkboxChange">
		          <label class="checkbox-item">
		            <checkbox value="check" :checked='true' color="#A1B1E7" class="checkbox" /> <!-- 勾选框 -->
		          </label>
		        </checkbox-group>
		    <text class="tip-text">勾选后生成的穿搭方案将开启定位，结合天气哦！</text>
		  </view>
		
		  <!-- 下部分：天气信息 -->
		  <view class="section3-bottom">
		    <view class="weather-left">
		       <view class="text1">{{ formattedDate }}</view>
		      	<view class="text">湿度：{{ weatherData.humidity }}%</view>
		      	<view class="text">温度：{{ weatherData.temperature }}°C</view>
		      	<view class="text">天气：{{ weatherData.condition }}</view>
		      	<view class="text">风向：{{ weatherData.winddirection }}</view>
		      	<view class="text">风力：{{ weatherData.windpower }}级</view>
		    </view>
		    <view class="weather-right">
				<view class="text1">当前所在城市：</view>
				<view class="text2">{{ currentCity }}</view>
				<view class="text1">修改定位城市：</view>
				<view class="uni-list-cell-db">
					<uni-data-picker
						popup-title="请选择所在地区"
						:localdata="classDataTree"
						v-model="classValue"
						@change="onchange"
						@nodeclick="handleNodeClick"
						@popupopened="handlePopupOpened"
						@popupclosed="handlePopupClosed"
						@inputclick="handleInputClick"
					></uni-data-picker>
				</view>
		    </view>
		  </view>
		</view>

		<!-- 第四部分：广告组合位 -->
		<view class="section section4">
			<swiper :indicator-dots="true" :autoplay="true" :interval="5000" :circular="true">
				<swiper-item v-for="(ad, index) in ads" :key="index">
					<image :src="ad.image" class="ad-image" />
				</swiper-item>
			</swiper>
		</view>

	</view>
</template>

<script>
import setting from '../../setting';
import {classDataTree} from "/pages/picker_region_1.js"
export default {
	data() {
		return {
			classValue: '110100', // 设置默认值或通过后端获取
			classDataTree: classDataTree,
			searchQuery: '',
			selectedKeywords: [],
			weatherData: {
				temperature: 0,
				condition: '--',
				winddirection: '--',
				windpower: 0,
				humidity: 0
			},
			formattedDate: '', // 使用计算属性替代this.getCurrentDate()
			isLocationModalVisible: false,
			currentCity: '--', // 当前城市
			currentCityy: '--',
			adCode: '',   //地理编码
			latitude: null, // 纬度
			longitude: null, // 经度
			ads: [
				{ image: '/static/ad1.jpg' },
				{ image: '/static/ad2.jpg' },
				{ image: '/static/ad3.jpg' },
				{ image: '/static/ad4.jpg' }
			],
			allKeywords: [
				'正式', '通勤', '运动', '休闲', '甜美', '复古', '新中式', '辣妹', '古风', '极简', '嘻哈', '优雅', '哥特', '度假风', '学院风',
			],
			filteredKeywords: [],
			checked: true, // 用于绑定勾选框的状态
			postion: ''
		};
	},
	created() {
		// 初始化日期
		this.formattedDate = this.getCurrentDate();
		
		// 如果勾选了，则获取位置
		if (this.checked === true) {
			this.getLocation();
		}
	},
	methods: {
		onchange() {
			const adCode = this.classValue;
			this.getWeatherByLocation(adCode, () => {
				// 在 getWeatherByLocation 完成后执行
					this.currentCity = this.currentCityy;
			});
		},
		// 添加这些处理函数以解决未定义的问题
		handleNodeClick(node) {
			console.log('Node clicked:', node);
		},
		handlePopupOpened() {
			console.log('Popup opened');
		},
		handlePopupClosed() {
			console.log('Popup closed');
		},
		handleInputClick() {
			console.log('Input clicked');
		},
		checkboxChange(event) {
			if (Array.isArray(event.detail.value) && event.detail.value.length) {
					        // 选中的操作
				this.checked = true; // 先将其设置true
				this.getLocation();
				checkOpenId().then((isValid) => {
					if (!isValid) {
					    this.checked = false;
				    }
			    });
			} else {
					this.checked = false;
			}
		},
		getCurrentDate() {
		    const date = new Date();
		    const year = date.getFullYear();
		    const month = String(date.getMonth() + 1).padStart(2, '0'); // Get month (0-11), adding 1 for 1-12
		    const day = String(date.getDate()).padStart(2, '0'); // Get day (1-31)
		
		    return `${year}-${month}-${day}`;
		},

		// 模糊搜索关键词
		search() {
			this.filteredKeywords = this.allKeywords.filter(keyword => 
				keyword.includes(this.searchQuery)
			);
		},

		// 切换关键词选中状态
		toggleKeywordSelection(keyword) {
			if (this.selectedKeywords.includes(keyword)) {
				this.selectedKeywords = this.selectedKeywords.filter(item => item !== keyword);
			} else {
				this.selectedKeywords.push(keyword);
			}
		},

		// 跳转到推荐页面
		async goToRecommendPage() {
			// 先获取推荐结果
			const recommendations = await this.getOutfitRecommendations();
			
			if (!recommendations) return;
			
			// 准备传递到推荐页的数据
			const dataToSend = {
				isChecked: this.checked,
				weatherData: this.weatherData,
				theme: this.selectedKeywords,
				recommendations: recommendations // 添加推荐结果
			};
			
			// 编码并跳转
			const encodedData = encodeURIComponent(JSON.stringify(dataToSend));
			uni.navigateTo({
				url: `/pages/Recommend/Recommend?data=${encodedData}`
			});
		},
		async getOutfitRecommendations() {
			try {
				// 准备请求数据（与后端要求的格式匹配）
				const requestData = {
					user_id: uni.getStorageSync('user_id'), // 实际项目中应从用户系统获取
					weather: this.weatherData.condition,
					temperature: this.weatherData.temperature,
					theme: this.selectedKeywords.join('，'), // 中文逗号分隔
					date: this.getCurrentDate(),
					season: this.getSeasonFromDate(),
					n_recommendations: 1 // 默认请求1个推荐
				};
				
				// 发送POST请求
				const response = await uni.request({
					url: setting.url+'/api/recommend_outfit', // 替换为实际API地址
					method: 'POST',
					data: requestData,
					header: {
						'Content-Type': 'application/json'
					}
				});
				
				// 处理响应
				if (response.statusCode === 200) {
					const result = response.data;
					return result.recommendations;
				} else {
					throw new Error(response.data.error || '获取推荐失败');
				}
			} catch (error) {
				console.error('获取推荐出错:', error);
				uni.showToast({
					title: '获取推荐失败',
					icon: 'none'
				});
				return null;
			}
		},
		getSeasonFromDate() {
			const month = new Date().getMonth() + 1;
			if (month >= 3 && month <= 5) return '春季';
			if (month >= 6 && month <= 8) return '夏季';
			if (month >= 9 && month <= 11) return '秋季';
			return '冬季';
		},
		getLocation() {
			const key = 'd9c5817d79996f4f3a4efd20e1a72e2d'; // 高德 Key
			uni.request({
				url: `https://restapi.amap.com/v3/ip?key=${key}`,
				method: 'GET',
				success: (res) => {
					if (res.statusCode === 200 && res.data.status === '1') {
						const ipInfo = res.data;
						console.log(ipInfo,res);
						this.adCode = ipInfo.adcode;
						this.classValue = ipInfo.adcode;
						this.getWeatherByLocation(ipInfo.adcode);
						// 将 IP 信息存储到页面数据中
						this.ipAddress = ipInfo.ip;
						this.currentCity = ipInfo.province+' '+ ipInfo.city;
					} else {
						console.error('获取 IP 信息失败:', res.data);
						uni.showToast({
							title: '获取 IP 信息失败，请重试',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					console.error('请求失败:', err);
					uni.showToast({
						title: '网络请求失败，请检查网络连接',
						icon: 'none'
					});
				}
			});
		},
		// 根据经纬度获取天气数据
		getWeatherByLocation(adCode, callback) {
			const apiKey = 'd9c5817d79996f4f3a4efd20e1a72e2d'; // 高德地图 API Key
			const url = `https://restapi.amap.com/v3/weather/weatherInfo?key=${apiKey}&city=${adCode}`;
		
			uni.request({
				url: url,
				success: (res) => {
					if (res.data.status === '1' &&  res.data.lives.length > 0) {
						console.log(res);
						const weatherInfo = res.data.lives[0];
						this.weatherData = {
							temperature: weatherInfo.temperature, // 温度
							condition: weatherInfo.weather, // 天气状况
							winddirection: weatherInfo.winddirection, // 风向
							windpower: weatherInfo.windpower, // 风力
							humidity: weatherInfo.humidity // 湿度
						};
						this.currentCityy = res.data.lives[0].province + ' ' + res.data.lives[0].city;
						console.log(this.currentCityy);
		
						// 调用回调函数
						if (callback) {
							callback();
						}
					} else {
						console.error('获取天气数据失败:', res.data);
						uni.showToast({
							title: '获取天气数据失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					console.error('请求天气接口失败:', err);
					uni.showToast({
						title: '请求天气接口失败',
						icon: 'none'
					});
				}
			});
		},

		// 选择城市并更新天气数据
		selectCity(city) {
			this.currentCity = city;
			this.closeLocationModal();
			// 根据城市名称获取经纬度
			this.getLocationByCity(city);
		},
	},
	
	// 初始化页面时自动进行一次搜索
	mounted() {
		this.search();
	}
};
</script>

<style scoped>
.container {
	padding: 20rpx;
	display: flex;
	flex-direction: column;
	height:100%;
	box-sizing: border-box; 
}

.section {
	margin-bottom: 20rpx;
	justify-content: space-between;
	overflow: hidden;
}

.section1 {
	max-height: 25%;  /* 统一设置整个区域的高度 */
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.search-box {
	display: flex;
	width: 100%;
	justify-content: space-between;
}

.search-input {
	width: 70%;
	padding: 8rpx;
	border: 1rpx solid #ccc;
	border-radius: 4rpx;
	height:56rpx;  /* 设置搜索框高度 */
	box-shadow: inset 1rpx 1rpx 2rpx rgba(0, 0, 0, 0.2); /* 内部阴影效果 */
	font-size: 28rpx;
}

.search-btn, .generate-btn {
	padding: 4rpx 8rpx;
	border: 1rpx solid black;
	background-color: #FFF200;
	border-radius: 10rpx;
	color: black;
	cursor: pointer;
	font-size:24rpx;
	width: 12%;
	box-shadow: 4rpx 4rpx 3rpx rgba(0, 0, 0, 0.3);  
}

.section2 {
	height: 28%; /* 设定一个固定高度让关键词部分可以上下滑动 */
	box-shadow:  4rpx 4rpx 5rpx rgba(0,0,0,0.5);
	border-radius: 10rpx;
	margin-top: 20rpx;
	padding:10rpx;
	overflow-y: auto;
}

.keyword-list {
	display: flex;
	flex-direction: column;
}

.keyword-row {
	display: flex;
	flex-wrap: wrap;  /* 允许关键词换行 */
	justify-content: space-between; /* 使关键词紧凑排列 */
}

.keyword-item {
	width: 20%; /* 每行显示三个关键词，适当调整宽度 */
	margin: 10rpx 5rpx;  /* 控制关键词之间的间距 */
	padding: 10rpx;
	border: thick double #FFC90E;
	border-radius: 50% 20% / 10% 40%;
	text-align: center;
	font-size: 24rpx;
	cursor: pointer;
	box-sizing: border-box;
	transition: box-shadow 0.3s ease;  /* 增加平滑过渡效果 */
}

.keyword-item.selected {
	background-color: #FFFB89;
	box-shadow: 4rpx 4rpx 8rpx rgba(0, 0, 0, 0.4);
}

.section3 {
  height: 25%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start; /* 改为从顶部开始排列 */
  gap: 20rpx; /* 微小间距 */
  border: 1rpx dashed #25C253;
  border-radius: 10rpx;
  margin-top: 15rpx;
}

.section3-top {
  display: flex;
  align-items: center;
  padding: 10rpx;
  margin-bottom: 0;
}

.section3-bottom {
  display: flex;
  justify-content: space-between;
  padding: 10rpx; /* 统一内边距 */
  padding-top: 0;
}

.checkbox-container {
  display: flex;
  align-items: center;
}


.checkbox-item {
  display: flex;
  align-items: center;
}

.checkbox{
	transform:scale(0.7);
}

.tip-text {
  margin-left: 10rpx;
  font-size: 25rpx;
  color: #666;
}

.weather-left {
  width: 40%;
  margin-left: 10rpx;
}

.text{
  font-size:28rpx ;
}

.text1 {
  font-size: 28rpx;
  margin-bottom: 5rpx;
}

.text2{
  margin-bottom: 20rpx;
}

.weather-right {
  width: 60%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.location-btn {
  border: thick double #A1B1E7;
  box-shadow: 4rpx 4rpx 3rpx rgba(0, 0, 0, 0.3);
  color: black;
  border-radius: 20rpx;
  padding: 10rpx;
  font-size: 28px;
}

.section4 {
    height: 30%;
    /* 确保父链有明确高度 */
    margin-top: 15rpx;
    border-radius: 10rpx;
    box-shadow: 4rpx 4rpx 4rpx rgba(0,0,0,0.4);
    /* 关键：设置 swiper 撑满容器 */
    display: flex;
    flex-direction: column;
}

/* 关键：让 swiper 和 swiper-item 撑满父容器 */
.section4 swiper {
    flex: 1; /* 占满剩余空间 */
    width: 100%;
    min-height:150px;
}

.section4 swiper-item {
    width: 100%;
    height: 100%;
}

.ad-image {
    width: 100%;
    height: 100%;
    border-radius: 10rpx;
    /* 可选：防止图片拉伸 */
    object-fit: cover;
}

.modal {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
}

.modal-content {
	background-color: white;
	padding: 20px;
	border-radius: 4px;
	width: 80%;
	text-align: center;
}

.city-selector button {
	margin: 10px;
}
</style>